import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:interrogation/app/routes/app_pages.dart';
import 'package:interrogation/src/data/api.dart';
import 'package:interrogation/src/data/models/consultation_res.dart';

import '../../../../base/utils/logger.dart';
import '../../../../base/utils/socket.dart';
import '../../../../base/utils/storage_manager.dart';
import '../../../../data/models/char_record_res.dart';
import '../../../../data/models/doctor_list_res.dart';
import '../../../../data/models/get_consultation_res.dart';
import '../../../../main_service.dart';
import '../../../const.dart';

class ChatPageController extends GetxController {

  late IMSocket socket;
  get isDoctor => Get.find<MainService>().isDoctor;

  @override
  void onInit() {
    super.onInit();
    _initSocket();
  }

  @override
  void onReady() {
    super.onReady();
    onRefresh();
  }

  @override
  void onClose() {
    super.onClose();
  }
  void _initSocket() {
    String? token = StorageManager.getString(StorageConst.token);
    socket = IMSocket.init(AppConst.socketServerUrl + "?token=${token ?? ''}");
    loggy.info("socketAddress is: ${AppConst.socketServerUrl +
        "?token=${token ?? ''}"}");
    print("socketAddress is: ${AppConst.socketServerUrl +
        "?token=${token ?? ''}"}");
    socket.messageStream.listen((String event) {
      loggy.info("messageStream is: $event");
      try {
        Map<String, dynamic> data = jsonDecode(event);
        if (data['type'] == 'chat-message-receive') {

        }
      } catch (e) {
        loggy.error("Error parsing socket message: $e");
      }
    });
  }

   //查找消息的cid，在已经请求的数据中，则更新数据的消息内容
   //如果不在数据中，则添加数据
    onMessageHandler(){

    }


  //////////////////////////////////refresh/////////////////////////////////////

  var list = [].obs;

  ///refresh
  EasyRefreshController refreshController = EasyRefreshController(
      controlFinishLoad: true, controlFinishRefresh: true);
  int num = 0;
  int page = 1;
  int pageSize = 20;

  Future<void> onRefresh() async {
    try {
      page = 1;
      EasyLoading.show(status: 'loading...');
      List<ConsultationModel>? _list = await Api.getConsultationList(
        page: page,
        pageSize: pageSize,
      );
      if (_list != null) {
        num = _list.length;
        list.value = [..._list];
      }
    } catch (e) {
      loggy.error(e.toString());
    } finally {
      refreshController.finishRefresh();
      refreshController.resetHeader();
      EasyLoading.dismiss();
    }
  }

  Future<void> onLoad() async {
    try {
      page++;
      EasyLoading.show(status: 'loading...');
      List<ConsultationModel>? _list = await Api.getConsultationList(
        page: page,
        pageSize: pageSize,
      );
      if (_list != null) {
        num = _list.length;
        list.value = [...list.value, ..._list];
      }
    } catch (e) {
      loggy.error(e.toString());
    } finally {
      refreshController.finishLoad(
          num >= 20 ? IndicatorResult.success : IndicatorResult.noMore);
      refreshController.resetFooter();
      EasyLoading.dismiss();
    }
  }

//////////////////////////////////refresh/////////////////////////////////////
}
